package com.leon.agent.web.controller.common;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.util.crypto.WxMpCryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhaojinliang
 * @version 1.0.0
 * @date 2025/5/23
 * @description TODO
 */
@RestController
@Slf4j
@RequestMapping("/wechat")
public class WechatEventController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxMpConfigStorage wxMpConfigStorage;

//    private final String TOKEN = "你的Token";
//    private final String ENCODING_AES_KEY = "你的EncodingAESKey";
//    private final String APP_ID = "你的第三方平台AppID";

    /**
     * 处理微信验证请求（GET）
     */
    @GetMapping("/callback")
    public String verify(@RequestParam("signature") String signature,
                         @RequestParam("timestamp") String timestamp,
                         @RequestParam("nonce") String nonce,
                         @RequestParam("echostr") String echostr) {
        // 实际需要校验签名，此处直接返回echostr（仅示例）
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            return "非法请求";
        }
        WxMpCryptUtil cryptUtil = new WxMpCryptUtil(wxMpConfigStorage);
        // 企业号应用在开启回调模式的时候，会传递加密echostr给服务器，需要解密并echo才能接入成功
        return cryptUtil.decrypt(echostr);
    }

    /**
     * 接收微信事件推送（POST）
     */
    @PostMapping("/callback")
    public String handleEvent(@RequestParam("signature") String signature,
                              @RequestParam("timestamp") String timestamp,
                              @RequestParam("nonce") String nonce,
                              @RequestBody String encryptedData) {
        try {
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(encryptedData, wxMpConfigStorage, timestamp, nonce, signature);


            log.info("接收到微信事件推送：{}", inMessage);
//            // 解密消息
//            WXBizMsgCrypt crypt = new WXBizMsgCrypt(TOKEN, ENCODING_AES_KEY, APP_ID);
//            String decryptedXml = crypt.decryptMsg(signature, timestamp, nonce, encryptedData);
//
//            // 解析XML
//            Document doc = DocumentHelper.parseText(decryptedXml);
//            Element root = doc.getRootElement();
//            String ticket = root.elementText("ComponentVerifyTicket");
//
//            // 存储票据（示例仅打印）
//            System.out.println("ComponentVerifyTicket: " + ticket);

            // 必须返回success
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}
